//
//  UIImage+Qrcode.m
//  HSCategoryKit
//
//  Created by huang on 2018/8/1.
//

#import "UIImage+Qrcode.h"

@implementation UIImage (Qrcode)

#pragma mark 生成二维码图片
+ (UIImage *)imageWithRUL:(NSString *)url imageWidth:(CGFloat)imageWidth
{
    CGFloat size = imageWidth*0.2;
    
    //2.创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    //3.恢复默认
    [filter setDefaults];
    
    //4.给过滤器添加数据
    NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKey:@"inputMessage"];
    
    //5.获取输出的二维码
    CIImage *outputImage = [filter outputImage];
    
    //6.将CIImage转换成UIImage,并放大显示
    return [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:size];
}

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MAX(MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent)), 1.5);
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    UIImage *newImg = [UIImage imageWithCGImage:scaledImage];
    
    //3.释放
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    CGColorSpaceRelease(cs);
    CGImageRelease(scaledImage);
    return newImg;
}

@end
